<template>
  <el-card
    style="margin: 10px 15px"
    shadow="always"
    :body-style="{ padding: '20px' }"
  >
    <el-tree
      :data="menuList"
      show-checkbox
      node-key="id"
      ref="tree"
      :props="defaultProps"
      :default-expanded-keys="spreadArr"
    >
    </el-tree>

    <el-button type="primary" size="default" @click="saveHandler">
      保存
    </el-button>
    <el-button size="default" @click="cancelHandler">取消</el-button>
  </el-card>
</template>

<script>
import { reqMenuInfoByRole, reqRoleForAuth } from "@/api/role";
export default {
  name: "RoleTree",
  data() {
    return {
      roleId: "",
      roleName: "",
      menuList: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      idList: [],
      spreadArr: [],
    };
  },
  mounted() {
    const { id, roleName } = this.$route.query;
    this.roleId = id;
    this.roleName = roleName;
    this.getMenuInfo();
  },
  methods: {
    async getMenuInfo() {
      try {
        const result = await reqMenuInfoByRole(this.roleId);
        this.menuList = [result.children[0]];
        const menuInfo = this.getIdList(result.children[0].children);
        this.spreadArr = menuInfo;
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(menuInfo, true);
        });
      } catch (error) {
        this.$message.error("菜单信息获取失败");
      }
    },

    cancelHandler() {
      this.$router.replace({
        name: "RoleAdmin",
      });
    },

    getIdList(menuInfo) {
      menuInfo.forEach((item) => {
        if (item.select && item.level === 4) {
          this.idList.push(item.id);
        } else if (item.children) {
          this.getIdList(item.children);
        }
      });
      return this.idList;
    },
    //保存方法
    async saveHandler() {
      const allCheckIdList = this.$refs.tree.getCheckedKeys(true);
      const halfCheckedIdList = this.$refs.tree.getHalfCheckedKeys();
      const permissionId = allCheckIdList.concat(halfCheckedIdList).join(",");
      try {
        await reqRoleForAuth({ roleId: this.roleId, permissionId });
        this.$router.replace({
          name: "Role",
        });
        this.$message.success("保存成功");
      } catch (error) {
        this.$message.error("保存失败");
      }
    },
  },
};
</script>

<style scoped></style>
